package com.captain.special.二叉树.简单;

import com.captain.leetcode.TreeNode;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/5/8 16:24
 */
public class 根据二叉树创建字符串606 {
    public String tree2str(TreeNode root) {
        if (root.left == null && root.right == null) {
            return String.valueOf(root.val);
        }
        StringBuilder builder = new StringBuilder();
        recur(root, builder);
        return builder.toString();
    }

    public void recur(TreeNode node, StringBuilder builder) {
        if (node == null) {
            return;
        }
        //前序遍历
        builder.append(node.val);
        //如果左右节点都没有值,则无需记录
        if (node.left == null && node.right == null) {
            return;
        }
        //一定存在左节点或者右节点
        builder.append("(");
        //如果存在左节点,则记录其值,如果存在右节点,则记录()
        recur(node.left, builder);
        builder.append(")");
        if (node.right != null) {
            builder.append("(");
            recur(node.right,builder);
            builder.append(")");
        }
    }
}
